package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;

/*
库管类:
核心职责管理我们的数据仓库--数组或集合
这里的所有方法和功能都是给业务层用
 */
public class OtherStudentDao02 implements BaseStudentDao {
    private static ArrayList<Student> stu = new ArrayList<>();
    static {
        try {
            BufferedReader br=new BufferedReader(new FileReader("StudentServer\\stu1.txt"));

            String s;
            StringBuilder sb=new StringBuilder();
            while ((s=br.readLine())!=null){
                sb.append(s+" ");
            }
            String strStu = sb.toString();
           // System.out.println(strStu);
            String[] split = strStu.split(" ");
            for (int i = 0; i < split.length; i++) {
                String stuArr= split[i];
                String[] split1 = stuArr.split(",");
                Student student=new Student(split1[0],split1[1],split1[2],split1[3]);
                stu.add(student);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean addStudent(Student student) {
        boolean add = stu.add(student);
        reSave();
        return add;
    }


    public Student[] findAllStudent() {
        Student[] stus = new Student[stu.size()];
        Student[] students = stu.toArray(stus);
        return students;
    }

    public void deleteStudent(String delId) {
        int index = getIndex(delId);
        stu.remove(index);
        reSave();
    }

    public int getIndex(String id) {
        int index = -1;
        for (int i = 0; i < stu.size(); i++) {
            Student student = stu.get(i);
            if (student != null && student.getSid().equals(id)) {
                index = i;
            }
        }
        return index;
    }

    public void updateStudent(String updateId, Student newStu) {

        int index = getIndex(updateId);
        stu.set(index, newStu);
        reSave();
    }

    public void reSave() {
        try {
            BufferedWriter bw=new BufferedWriter(new FileWriter("StudentServer\\stu1.txt"));
            for (Student student : stu) {
                String string = student.toString();
                bw.write(string);
                bw.newLine();
                bw.flush();
            }
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
